{% extends "base.html" %}

{% block title %}Home - PinCaiCai 2.0{% endblock %}

{% block content %}
<!-- Hero section -->
<div class="hero-section bg-success text-white py-5">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-6">
                <h1 class="display-4 fw-bold mb-3">PinCaiCai 2.0</h1>
                <h2 class="h3 mb-4">Fresh ingredients, quality life</h2>
                <p class="lead mb-4">Daily fresh delivery, from farm to table, providing you with the highest quality ingredient experience</p>
                <a href="/all" class="btn btn-light btn-lg">Shop Now</a>
            </div>
            <div class="col-lg-6">
                <div class="text-center">
                    <i class="fas fa-leaf fa-10x opacity-75"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Carousel -->
<div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel">
    <div class="carousel-indicators">
        <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active"></button>
        <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1"></button>
        <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2"></button>
    </div>
    <div class="carousel-inner">
        <div class="carousel-item active">
            <div class="carousel-caption d-none d-md-block bg-dark bg-opacity-50 rounded">
                <h5>Fresh Vegetables</h5>
                <p>Daily fresh harvest, quality guaranteed</p>
            </div>
        </div>
        <div class="carousel-item">
            <div class="carousel-caption d-none d-md-block bg-dark bg-opacity-50 rounded">
                <h5>Quality Meats</h5>
                <p>Premium meats, rich in nutrition</p>
            </div>
        </div>
        <div class="carousel-item">
            <div class="carousel-caption d-none d-md-block bg-dark bg-opacity-50 rounded">
                <h5>Fresh Fruits</h5>
                <p>Seasonal fruits, sweet and delicious</p>
            </div>
        </div>
    </div>
    <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev">
        <span class="carousel-control-prev-icon"></span>
    </button>
    <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next">
        <span class="carousel-control-next-icon"></span>
    </button>
</div>

<!-- Category navigation -->
<div class="container my-5">
    <div class="row">
        <div class="col-md-3 mb-4">
            <div class="card product-card h-100">
                <div class="card-body text-center">
                    <i class="fas fa-leaf fa-3x text-success mb-3"></i>
                    <h5 class="card-title">Vegetables</h5>
                    <p class="card-text">Fresh vegetables, rich in nutrition</p>
                    <a href="/vegetables" class="btn btn-success">View Products</a>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card product-card h-100">
                <div class="card-body text-center">
                    <i class="fas fa-drumstick-bite fa-3x text-danger mb-3"></i>
                    <h5 class="card-title">Meats</h5>
                    <p class="card-text">Quality meats, guaranteed quality</p>
                    <a href="/meats" class="btn btn-danger">View Products</a>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card product-card h-100">
                <div class="card-body text-center">
                    <i class="fas fa-apple-alt fa-3x text-warning mb-3"></i>
                    <h5 class="card-title">Fruits</h5>
                    <p class="card-text">Seasonal fruits, sweet and delicious</p>
                    <a href="/fruits" class="btn btn-warning">View Products</a>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card product-card h-100">
                <div class="card-body text-center">
                    <i class="fas fa-fish fa-3x text-info mb-3"></i>
                    <h5 class="card-title">Seafood</h5>
                    <p class="card-text">Fresh seafood, nutritious and delicious</p>
                    <a href="/seafood" class="btn btn-info">View Products</a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recommended products -->
<div class="container my-5">
    <div class="text-center mb-5">
        <h2 class="display-5 fw-bold text-success mb-3">Featured Products</h2>
        <p class="lead text-muted">Carefully selected quality products for you, each one has been strictly screened</p>
        <hr class="w-50 mx-auto text-success">
    </div>
    <div class="row" id="featured-products">
        <!-- Products will be dynamically loaded here via JavaScript -->
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// Load recommended products
document.addEventListener('DOMContentLoaded', function() {
    fetch('/api/products/recommended')
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('featured-products');
            if (data.recommended && data.recommended.length > 0) {
                data.recommended.forEach(product => {
                    const col = document.createElement('div');
                    col.className = 'col-md-3 mb-4';
                    col.innerHTML = `
                        <div class="card product-card h-100">
                            <div class="card-img-top d-flex align-items-center justify-content-center" style="height: 150px; background-color: #f8f9fa; font-size: 3rem;">
                                ${product.emoji || '📦'}
                            </div>
                            <div class="card-body d-flex flex-column">
                                <h5 class="card-title">${product.name}</h5>
                                <p class="card-text">${product.description || ''}</p>
                                <p class="text-success fw-bold">¥${product.price}</p>
                                <p class="text-muted">Stock: ${product.stock}</p>
                                
                                <!-- Quantity selector -->
                                <div class="mb-3">
                                    <label class="form-label">Quantity:</label>
                                    <div class="input-group">
                                        <button class="btn btn-outline-secondary" type="button" onclick="changeQuantityIndex('${product.category}', ${product.product_id}, -1)">-</button>
                                        <input type="number" class="form-control text-center" id="quantity-${product.category}-${product.product_id}" value="1" min="1" max="${product.stock}">
                                        <button class="btn btn-outline-secondary" type="button" onclick="changeQuantityIndex('${product.category}', ${product.product_id}, 1)">+</button>
                                    </div>
                                </div>
                                
                                <!-- Action buttons -->
                                <div class="mt-auto">
                                    <button class="btn btn-primary w-100 mb-2" onclick="addToCart('${product.category}', ${product.product_id})">Add to Cart</button>
                                    <button class="btn btn-success w-100" onclick="buyNow('${product.category}', ${product.product_id})">Buy Now</button>
                                </div>
                            </div>
                        </div>
                    `;
                    container.appendChild(col);
                });
            } else {
                container.innerHTML = '<div class="col-12 text-center"><p>No recommended products available</p></div>';
            }
        })
        .catch(error => {
            console.error('Error loading featured products:', error);
            document.getElementById('featured-products').innerHTML = '<div class="col-12 text-center"><p>Failed to load products</p></div>';
        });
});

function changeQuantityIndex(category, productId, change) {
    const input = document.getElementById(`quantity-${category}-${productId}`);
    const currentValue = parseInt(input.value);
    const newValue = Math.max(1, Math.min(currentValue + change, parseInt(input.max)));
    input.value = newValue;
}

function addToCart(category, productId) {
    const quantity = parseInt(document.getElementById(`quantity-${category}-${productId}`).value);
    
    fetch('/api/cart/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            category: category,
            product_id: productId,
            quantity: quantity
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`Added ${quantity} items to cart!`);
        } else if (data.error && data.error.includes('login')) {
            alert('Please login first before adding to cart!');
        } else {
            alert('Add failed: ' + (data.error || data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error adding to cart:', error);
        alert('Add failed, please try again');
    });
}

function buyNow(category, productId) {
    const quantity = parseInt(document.getElementById(`quantity-${category}-${productId}`).value);
    
    if (confirm(`Are you sure you want to buy ${quantity} items?`)) {
        // Create order directly
        fetch('/api/orders', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                items: [{
                    category: category,
                    product_id: productId,
                    quantity: quantity
                }]
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message && data.message.includes('success')) {
                alert('Order created successfully!');
                window.location.href = '/orders';
            } else if (data.error && data.error.includes('login')) {
                alert('Please login first before purchasing!');
            } else {
                alert('Purchase failed: ' + (data.error || data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error buying now:', error);
            alert('Purchase failed, please try again');
        });
    }
}
</script>
{% endblock %}
